package app

import (
	"fmt"
	"github.com/duke-git/lancet/v2/slice"
	"kvmc/pkg/uix"
)

type ListOption struct {
	ClusterName string
	All         bool
}

func (m *Manager) List(option *ListOption) {
	m.listDefaultCluster()
	m.listCenter()
	m.listNodes(option)
}

func (m *Manager) listDefaultCluster() {
	fmt.Println("Default: ", m.DefaultCluster)
	fmt.Println()
}

func (m *Manager) listCenter() {
	infos := make([][]string, 0, 2)
	infos = append(infos, []string{"addr", "username", "private_key"})
	if m.Center != nil {
		infos = append(infos, []string{
			m.Center.Addr,
			m.Center.Username,
			m.Center.PrivateKey,
		})
	}
	fmt.Println("Center:")
	uix.Table(infos)
	fmt.Println()
}

func (m *Manager) listNodes(option *ListOption) {
	nodes := make([]*Node, 0)
	data := make([][]string, 0, len(nodes))

	if option.All {
		nodes = m.GetAllNodes()
	} else {
		nodes = m.GetClusterNodes(option.ClusterName)
	}
	data = append(data, []string{"cluster", "name", "hostname", "ip"})
	for _, node := range nodes {
		data = append(data, []string{
			node.ClusterName,
			node.Name,
			node.Hostname,
			node.IP,
		})
	}
	if len(data) > 1 {
		slice.SortBy(data[1:], func(a, b []string) bool {
			return a[0] < b[0] || (a[0] == b[0] && a[1] < b[1])
		})
	}
	fmt.Println("Nodes:")
	uix.Table(data)
	fmt.Println()
}
